import React from 'react';

import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import axios from 'axios';

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

class PicturesWall extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      previewVisible: false,
      previewImage: '',
      previewTitle: '',
      fileList: []
    };
  }

  componentDidMount() {
    const { fileList } = this.state;
    axios.get('/file/list').then((res) => {
      console.log(res.data);
      const { data } = res.data || {};
      data.forEach((i, index) => {
        fileList.push({
          uid: index,
          name: i,
          status: 'done',
          url: `/${i}`
        });
      });
      this.setState({ fileList });
    }).catch(() => {});
  }

  // 关闭详情模态框
  handleCancel = () => this.setState({ previewVisible: false });

  // 设置详情模态框数据
  handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
    });
  };

  // 上传文件发生变化
  handleChange = ({ fileList }) => this.setState({ fileList });

  static onRemove = (a) => {
    console.log(a.name);
    axios.post('/file/delete', { fileList: [a.name] }).then((res) => {
      console.log(res);
    });
  };

  // startUpload = ({ file, filename, headers }) => {
  //   console.log(file, filename, headers, 'gggg');
  //   const formData = new FormData();
  //   formData.append(filename, file);
  //   axios.post(
  //     '/file/uploadOne',
  //     formData,
  //     {
  //       'Content-type': 'multipart/form-data'
  //     }
  //   ).then(res => {
  //     console.log(res);
  //     // 设置进度  设置结果
  //   });
  // };

  render() {
    const {
      previewVisible, previewImage, fileList, previewTitle 
    } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );

    return (
      <>
        <Upload
            action="/file/uploadOne" // 上传的接口
            listType="picture-card"
            fileList={fileList} // 已经上传的list
            onPreview={this.handlePreview} // 点击预览的回调
            onChange={this.handleChange} // 上传状态发生改变时的回调
            onRemove={this.onRemove}
            // customRequest={this.startUpload}
            headers={{ Authorization: window.sessionStorage.token }} // 设置上传的token
        >
          {fileList.length >= 8 ? null : uploadButton}
        </Upload>
        {/* 详情的模态框 */}
        <Modal
            visible={previewVisible}
            title={previewTitle}
            footer={null}
            onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    );
  }
}

export default PicturesWall;
